<template>
	<view class="search">
		<view class="searchButtom">
			<uni-search-bar @focus="onClickSearch" @confirm="onConfirm" placeholder="搜索"  v-model="queryParams.keyword" :radius="50" :focus="true"></uni-search-bar>
		</view>
		<view class="main"  v-if="isShowzj">
			<view class="top"></view>
			<view ref="searchHistoryRef" :style="{maxHeight:maxHeightTo>0 ? maxHeightTo.toFixed(0)+'px' : ''}"  class="searchHistory" :class="{onClick:isMoreBottom}" v-show="historySearch.length">
				
				<view class="title">
					<view class="text">最近搜索</view>
					<view class="icon" @click="onDelete">
						<uni-icons type="trash" size="25" color="#666" ></uni-icons>
					</view>
				</view>
				<view class="searchHistoryBox">
					<view id="searchHistoryBoxItem" @click="onClickBox(i)" class="box" v-for="i in historySearch" :key="i">{{i}}</view>
				</view>
				
				
			</view>
			
			<view class="bottom" @click="onIsMoreBottom" v-if="moreHistory">
				<view class="text">{{!isMoreBottom?'更多历史':'收起历史'}}</view>
				<view class="icon" :class="{isIcon:isMoreBottom}">
					<uni-icons color="#666" type="down" size="22"></uni-icons>
				</view>
			</view>
			
			<view class="popularSearch">
				<view class="title">热门搜索</view>
				<view class="popularSearchBox">
					<view @click="onClickBox(i)" class="box" v-for="i in popularSearches" :key="i">{{i}}</view>
				</view>
			</view>
		</view>
		
		<!-- 空状态 -->
		<view class="noSearch"  v-if="noSearch">
			<uv-empty mode="search" icon="/static/images/kzt.png"></uv-empty>
		</view>
		
		<view v-else>
		
			<view class="listImg">
				<view class="list" v-if="classList.length">
					<navigator v-for="item in classList" :key="item._id" :url="'/pages/preview/preview?_id='+item._id" class="item">
						<image @click="onImage" :src="item.smallPicurl" mode="aspectFill"></image>
					</navigator>
				</view>
				<view class="loading" v-if="classList.length">
					<uni-load-more :status="onData ? 'no-more' : 'loading'"></uni-load-more>
				</view>
			</view>
		</view>
		
	</view>
	
	

	
	
</template>

<script setup>
import { ref,onMounted } from 'vue';
import {searchWallApi} from '@/api/apis.js'
import {onReachBottom} from '@dcloudio/uni-app'
import { usePreviewStore } from '@/store/preview.js';
	const previewStore = usePreviewStore()
	const onImage = () => {
		previewStore.setClassList(classList.value)
	}
//输入框输入的内容
const queryParams = ref({
	pageNum:1,
	pageSize:12,
	keyword:""
})

//控制是否显示更多历史按键
const moreHistory = ref(false)

//获取最近搜索盒子的高度
const getBoxHeight = ()=>{
	uni.createSelectorQuery()
	   .select('.searchHistoryBox') // 替换为实际class或id
	   .boundingClientRect(rect => {
	     console.log('盒子高度:', rect?.height)
		 if(rect?.height > 112) moreHistory.value = true
	   }).exec()
}

//获取盒子在三行时的高度
const maxHeightTo = ref(
+uni.getStorageSync('maxHeight') ? uni.getStorageSync('maxHeight') : 0
)
const searchHistoryRef = ref(null)

//获取行数
const calculateRows = () => {
  uni.createSelectorQuery()
    .selectAll('#searchHistoryBoxItem') // 替换为实际子元素class
    .boundingClientRect(rects => {
      let rows = 1
      rects.forEach((rect, index) => {
        if (index > 0 && rect.top !== rects[index-1].top) {
          rows++
        }
      })
      console.log('当前行数:', rows)
	  if(rows>=3) moreHistory.value = true
	  if(rows === 3 ){
		  uni.createSelectorQuery()
		     .select('.searchHistory') // 替换为实际class或id
		     .boundingClientRect(rect => {
			   maxHeightTo.value = rect?.height
			   uni.setStorageSync('maxHeight',rect?.height)
			   // searchHistoryRef.value.style.maxHeight=maxHeight.value
		     }).exec()
	  }
    }).exec()
}


onMounted(()=>{
	// getBoxHeight()
	calculateRows()
	// uni.createSelectorQuery()
	//    .select('.searchHistory') // 替换为实际class或id
	//    .boundingClientRect(rect => {
	// 	   console.log(rect);
	//      console.log('盒子高度:', rect?.height)
	// 	maxHeight.value = rect?.height
	// 	maxHeightTo.value = rect?.height
	// 	console.log(searchHistoryRef.value);
	//    }).exec()
})
//搜索历史
const historySearch = ref(uni.getStorageSync("historySearch") || [])
//热门搜索
const popularSearches = ref(['美女','帅哥','狗狗','猫猫'])

//图片数据
const classList = ref([])
//控制最近搜索的显示
const isShowzj=ref(true)

const onConfirm = e => {
	if(!e.value.trim()) return uni.showToast({
		icon:'none',
		title:"请输入内容"
	})
	if(e.value.trim()) historySearch.value = [...new Set([e.value,...historySearch.value])]
	classList.value = []
	searchWall()
	// queryParams.value.keyword = ''
	uni.setStorageSync("historySearch",historySearch.value)
	isShowzj.value = false
	
}
//删除最近搜索
const onDelete = () =>　{
	uni.showModal({
		content:"确定要清除历史搜索记录吗?",
		success(res) {
			if(res.confirm){
				historySearch.value = []
				uni.removeStorageSync("historySearch")
				moreHistory.value = false
			}
		}
	})
}
//点击历史搜索把值传入到搜索框
const onClickBox = e => {
	historySearch.value = [...new Set([e,...historySearch.value])]
	uni.setStorageSync("historySearch",historySearch.value)
	queryParams.value.keyword = e
	searchWall()
	isShowzj.value = false
}

const onData = ref(false)
//没有搜索到数据时
const noSearch=ref(false)
//调用接口获取图片
const searchWall = async () => {
	// getBoxHeight()
	calculateRows()
	let res = await searchWallApi(queryParams.value)
	classList.value = [...classList.value,...res]
	if(queryParams.value.pageSize > res.length) {
		onData.value = true
	} 
	if(res.length == 0) noSearch.value = true
}
//触底加载
onReachBottom(()=>{
	if(onData.value) return
	queryParams.value.pageNum++
	searchWall()
})

//点击搜索框清空图片列表
const onClickSearch = () =>{
	classList.value = []
	isShowzj.value = true
	noSearch.value=false
}

//点击更多展示更多历时搜索记录
const isMoreBottom = ref(false)
const onIsMoreBottom = () => {
	isMoreBottom.value = !isMoreBottom.value
	!isMoreBottom.value ? maxHeightTo.value = +uni.getStorageSync('maxHeight') : maxHeightTo.value = 1000
	// maxHeight.value = 1000
}
</script>

<style lang="scss" scoped>
.search{

	.noSearch{
		padding-top: 10vh;
	}
	.listImg{
		padding-top: 120rpx;
		.loading{
			padding: env(safe-area-inset-bottom);
		}
	}
	position: relative;
	.searchButtom{
		position: fixed;
		z-index: 1;
		width: 100vw;
		background-color: #fff;
	}
	.top{
		height: 130rpx;
	}
	.searchHistory{
		transition: max-height 0.3s ease;
		padding: 0 20rpx;
		max-height: 270rpx;
		overflow: hidden;
		&.onClick{
			max-height: 1300rpx;
		}
		.title{
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 10rpx;
			.text{
				color: #666;
			}
		}
		
		.searchHistoryBox{
			display: flex;
			flex-wrap: wrap;
			align-content: space-between;
			.box{
				padding: 5rpx 20rpx;
				border-radius: 50rpx;
				background-color: #eee;
				line-height: 50rpx;
				max-width: 200rpx;
				width: max-content;
				margin: 0 10rpx 10rpx 0;
				white-space: nowrap;
				overflow: hidden;   
				text-overflow: ellipsis;
			}
		}
	}
	.bottom{
		 box-shadow: 0 -10rpx 10rpx 0rpx rgba(0 ,0, 0, 0.04);
		width: 100vw;
		display: flex;
		justify-content: center;
		align-items: center;
		color: #666;
		.icon{
			transition: all 0.3s ease;
			&.isIcon{
				transform: rotate(180deg);
			}
		}
	}
	.popularSearch{
		padding: 0 20rpx;
		.title{
			color: #666;
			margin-bottom: 10rpx;

		}
		.popularSearchBox{
			display: flex;
			flex-wrap: wrap;
			align-content: space-between;
			.box{
				padding: 5rpx 20rpx;
				border-radius: 50rpx;
				background-color: #eee;
				line-height: 50rpx;
				max-width: 200rpx;
				width: max-content;
				margin: 0 10rpx 10rpx 0;
				white-space: nowrap;
				overflow: hidden;   
				text-overflow: ellipsis;
			}
		}
	}
}
.list{
	padding: 5rpx;
	display: grid;
	grid-template-columns: repeat(3,1fr);
	gap: 5rpx;
	.item{
		height: 400rpx;
		image{
			width: 100%;
			height: 100%;
			display: block;
		}
	}

}
</style>
